package com.hzjy.common.core.controller;

import com.hzjy.common.utils.AppConst;
import com.hzjy.common.utils.AppResponse;
import com.hzjy.common.utils.EncryptionUtils;
import com.hzjy.common.utils.JSONUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

public class ApiBaseController extends BaseApiController
{
    /**
     * 请求验证
     */
    public String verificationRequest(HttpServletRequest request) {

        if (request.getHeader("send") == null || request.getHeader("sdate") == null || request.getHeader("token") == null)
        {
            // return "请求验证信息缺失";
            return "";
        }
        String send = request.getHeader("send");
        String sdate = request.getHeader("sdate");
        String token = request.getHeader("token");
        //toLowerCase()转小写
        String valtoken = EncryptionUtils.MD5((send + sdate + AppConst.DDPRINT_SECRETKEY).toLowerCase());
        if (token.equals(valtoken))
        {
            return "";
        }
        else
        {
            return "请求验证失败";
        }
    }
    /**
     * 获取token
     */
    public String getHeaderToken(HttpServletRequest request){
        return request.getHeader("token");
    }
    /**
     * 解析请求体转换成Bean对象
     */
    public static <T> T parseRequest(HttpServletRequest request, Class<T> clazz)
    {
        StringBuilder requestBuilder = new StringBuilder();
        BufferedReader reader = null;
        try
        {
            reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            String str = null;
            while ((str = reader.readLine()) != null)
            {
                requestBuilder.append(str);
            }
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
            return null;
        }
        System.out.println("app_request:->" + requestBuilder.toString());
        return JSON.parseObject(requestBuilder.toString(), clazz);
    }

    /**
     * 返回响应数据
     */
    protected void returnResponse(HttpServletResponse response, String responseInfo)
    {
        String sdate = getGMTDate();
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("send", AppConst.DDPRINT_SERVER);
        response.setHeader("sdate", sdate);
        response.setHeader("token", getToken(sdate));

        // String callback = this.getRequest().getParameter("callback");

        try
        {
            PrintWriter pw = response.getWriter();
            // pw.write(callback + "(" +responseInfo+")");
            pw.write(responseInfo);
            pw.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 返回响应当前时间
     */
    protected String getGMTDate()
    {
        Date sysdate = new Date();
        SimpleDateFormat df = new SimpleDateFormat(AppConst.HTTP_HEADER_DATE_FORMAT, Locale.ENGLISH);
        df.setTimeZone(TimeZone.getTimeZone(AppConst.HTTP_HEADER_TIME_ZONE));
        return df.format(sysdate);
    }

    /**
     * 返回错误响应
     */
    protected void returnError(HttpServletResponse response, String code, String describe)
    {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        AppResponse appresp = new AppResponse();
        appresp.setCode(code);
        appresp.setMessage(describe);
        returnResponse(response, JSON.toJSONString(appresp));
    }
    /**
     * @param requestCode
     * @param msg
     * @param data
     * @return Map<String,Object>
     * @throws
     * @Description:构建统一格式返回对象
     * @date 2019/08/31
     * @author shishun
     */
    public Map<String, Object> toResponsObject(int requestCode, String msg, Object data) {
        Map<String, Object> obj = new HashMap<String, Object>();
        obj.put("errno", requestCode);
        obj.put("errmsg", msg);
        if (data != null)
            obj.put("data", data);
        return obj;
    }

    public Map<String, Object> toResponsSuccess(Object data) {
        Map<String, Object> rp = toResponsObject(0, "执行成功", data);
        return rp;
    }

    public Map<String, Object> toResponsMsgSuccess(String msg) {
        return toResponsObject(0, msg, "");
    }

    public Map<String, Object> toResponsSuccessForSelect(Object data) {
        Map<String, Object> result = new HashMap<>(2);
        result.put("list", data);
        return toResponsObject(0, "执行成功", result);
    }

    public Map<String, Object> toResponsFail(String msg) {
        return toResponsObject(1, msg, null);
    }
    /**
     * 返回请求方的ip
     */
    public String getClientIp(HttpServletRequest request) {
        String xff = request.getHeader("X-Real-IP");
        if(xff!=null) {
            return xff;
        }
        xff = request.getHeader("x-forwarded-for");
        if (xff == null) {
            return "8.8.8.8";
        }
        return xff;
    }
    /**
     * 对传过来的json数据进行处理
     */
    public JSONObject getJsonRequest(HttpServletRequest request) {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
    /**
     * 返回token
     */
    protected String getToken(String sdate)
    {
        return EncryptionUtils.MD5((AppConst.DDPRINT_SERVER + sdate + AppConst.DDPRINT_SECRETKEY).toLowerCase());
    }

    /**
     * 返回响应数据
     */
    protected void returnResponse(HttpServletResponse response, String code,String message,Map data)
    {
        String sdate = getGMTDate();
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("send", AppConst.DDPRINT_SERVER);
        response.setHeader("sdate", sdate);
        response.setHeader("token", getToken(sdate));
        response.setHeader("Access-Control-Allow-Origin", "*");
        try
        {
            Map map=new HashMap();
            map.put("code", code);
            map.put("message", message);
            map.put("data", data);
            PrintWriter pw = response.getWriter();
            pw.write(JSONUtil.map2json(map));
            pw.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}